<?php
namespace app\mobile\controller;

use app\mobile\controller\BaseController;
use think\annotation\Route;
use think\facade\Cache;
use app\common\service\sms\Index as Sms;
use app\mobile\service\User as UserService;
use app\mobile\model\User as UserModel;
class Passport extends BaseController
{
	/**
	 * [用户登录]
	 * Author：上官钧墨
	 * @return [type] [description]
	 */
	public function login()
	{
		$data = $this->postData();
		if (!isset($data['mobile']) || !isMobile($data['mobile'])) {
			return $this->returnError('手机号错误');
		}
		if (!isset($data['code']) || !isCode($data['code'])) {
			return $this->returnError('验证码不能为空或格式错误');
		}
		$mobile = $data['mobile'];
		$code = $data['code'];

		// $is_code = cache('code_'.$mobile.'_'.$code);
		// if (!$is_code) {
		// 	return $this->returnError('验证码错误');
		// }
		// // 清除验证码
		// cache('code_'.$mobile.'_'.$code,null);
		
		$model = new UserModel;
		$detail = $model->detail(['mobile'=>$mobile]);
		$userInfo=json_decode(json_encode($detail),true);
		if ($userInfo) {
			# 存在用户信息，登录
			if (!$userInfo['status']) {
	            return $this->returnError($model->getError() ?: '登录失败, 账号不可用');
	        }
	        $detail->save(['last_login_time'=>time()]);
			$token = UserService::login($userInfo);
			return $this->returnSuccess([
	            'Authorization-Token' => $token,
	            'mobile' => $mobile,
	            'user_id' => $userInfo['user_id'],
	        ], '登录成功');
		}
		// 不存在，注册新用户
		$user_id = $model->insertGetId([
			'mobile'=>$mobile,
			'client_ource'=>source(),
			'create_time'=>time(),
			'update_time'=>time(),
			'last_login_time'=>time(),
		]);
		$detail = $model->detail(['user_id'=>$user_id]);
		$info=json_decode(json_encode($detail),true);
		$token = UserService::login($info);
		return $this->returnSuccess([
            'Authorization-Token' => $token,
            'mobile' => $mobile,
            'user_id' => $user_id,
        ], '登录成功');

	}
	/**
	 * [短信验证码发送]
	 * Author：上官钧墨
	 * @return [type] [description]
	 */
	public function sendSms()
	{
		$data = $this->postData();
		if (!isset($data['mobile']) || !isMobile($data['mobile'])) {
			return $this->returnError('手机号错误');
		}
		$mobile = $data['mobile'];
		$code = generate_code();
		cache('code_'.$mobile.'_'.$code,1,300);
		$AliSms = new Sms();
		$res = $AliSms->sendSms($mobile,$code);
		if ($res['status']) {
			return $this->returnSuccess($res['message']);
		}
		return $this->returnError($res['message']);

		$token = UserService::login();
	}






}
